﻿using System;
using System.Transactions;
using Abp.Dependency;
using Abp.Domain.Uow;
using Abp.EntityFrameworkCore.Uow;
using Abp.MultiTenancy;
using Hicap.AuthorizationServer.EntityFrameworkCore.Seed.Host;
using Microsoft.EntityFrameworkCore;

namespace Hicap.AuthorizationServer.EntityFrameworkCore.Seed
{
    public static class SeedHelper
    {
        private static IUnitOfWorkManager _unitOfWorkManager;

        public static void SeedHostDb(IIocResolver iocResolver)
        {
            WithDbContext<AuthorizationServerDbContext>(iocResolver, SeedHostDb);
        }

        public static void SeedHostDb(AuthorizationServerDbContext context)
        {
            context.SuppressAutoSetTenantId = true;
            new InitialHostDbBuilder(context, _unitOfWorkManager).Create();
        }

        private static void WithDbContext<TDbContext>(IIocResolver iocResolver, Action<TDbContext> contextAction)
            where TDbContext : DbContext
        {
            _unitOfWorkManager = iocResolver.ResolveAsDisposable<IUnitOfWorkManager>().Object;
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
            {
                var context = _unitOfWorkManager.Current.GetDbContext<TDbContext>(MultiTenancySides.Host);

                contextAction(context);

                uow.Complete();
            }
        }
    }
}